package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//[15]三数之和
public class ThreeSum15{
public static void main(String[] args) {
   Solution solution = new ThreeSum15().new Solution();
   
}

  //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        if (nums == null || nums.length<3 ) return null;
        List<List<Integer>> res = new ArrayList<>();

        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i>0 && nums[i] == nums[i-1]) continue;//去重
            int left = i+1;
            int right = nums.length-1;
            while (left < right){
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0){
                    ArrayList<Integer> detailList = new ArrayList<>(3);
                    detailList.add(nums[i]);
                    detailList.add(nums[left]);
                    detailList.add(nums[right]);
                    res.add(detailList);
                    left++;
                    while (left < right && nums[left]== nums[left-1]){left++;}//去重
                    right--;
                    while (left < right && nums[right]== nums[right+1]){right--;}//去重
                }else if ( sum > 0 ){
                    right--;
//                    while (left < right && nums[right]== nums[right+1]){right--;}//去重
                }else {
                    left++;
//                    while (left < right && nums[left]== nums[left-1]){left++;}//去重
                }

            }

        }

        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}